#include "SDL2/SDL.h"


int isExist = 0;
#define EVENT_REFRESH_VIDEO (SDL_USEREVENT + 0x01)
int refreshVideo(void *data) {
    while (isExist == 0) {
        SDL_Event event;
        event.type = EVENT_REFRESH_VIDEO;
        SDL_PushEvent(&event);
        SDL_Delay(40);
    }
    return 0;
}

//在播放框里面显示画框
int main(int argc, char **argv) {

    SDL_Init(SDL_INIT_VIDEO);
    const char *fileName = argv[1];

    //视频宽高
    int width = 640;
    int height = 360;

    SDL_Window *window = SDL_CreateWindow("DisplayVideo", 100, 100, width, height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
    if (window == NULL) {
        SDL_Log("SDL_CreateWindow failed:%s\n", SDL_GetError());
        return -1;
    }

    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == NULL) {
        SDL_Log("SDL_CreateRenderer failed: %s\n", SDL_GetError());
    }

    SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, width,height );
    if (texture == NULL) {

    }

    SDL_CreateThread(refreshVideo, "refreshVideo", NULL);
    FILE *fp = fopen(fileName, "rb");
    uint8_t buffer[width * height * 3 / 2];


    while (1) {

        SDL_Event event;
//        SDL_PollEvent(&event);
        SDL_WaitEvent(&event);
        if (event.type == SDL_Quit) {
            isExist = 1;
            break;
        } else if (event.type == EVENT_REFRESH_VIDEO) {
            memset(buffer, 0 , sizeof(buffer));
            int readSize = fread(buffer, 1, sizeof(buffer), fp);
            if (readSize != sizeof(buffer)) {
                fseek(fp, 0, SEEK_SET);
                readSize = fread(buffer, 1, sizeof(buffer), fp);
            }
            SDL_UpdateTexture(texture, NULL, buffer, width);
            SDL_RenderClear(renderer);
            SDL_RenderCopy(renderer, texture, NULL, NULL);
            SDL_RenderPresent(renderer);
        }
    }

    end:
//    SDL_Delay(5 * 1000);
    SDL_DestroyWindow(window);
    SDL_Quit();


    return 0;
}